import { defineStore, createPinia } from 'pinia'
import { computed, ref } from 'vue'
import { App } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { getUserInfoApi, getUserAccessRoutesApi } from '@/request/api/user'
import {
  desensitizeDataVerifyApi,
  desensitizeDataVerifyStatusApi,
  desensitizeDataVerifyExpireTimeApi,
} from '@/request/api/other'
import { getSortListApi } from '@/request/api/sort'
import { debounce } from '@/utils/func'

const pinia = createPinia()

// 封装路由初始化方法
export const initStore = (app: App<Element>) => {
  app.use(pinia)
}

// 在 Setup Store 中：
// ref() 就是 state 属性
// computed() 就是 getters
// function() 就是 actions

//
//
// 联网状态
export const useOnlineStatusStore = defineStore('onlineStatus', () => {
  const onlineStatus = ref<boolean>(true)
  const refresh = ref<string>()

  function setStatus(value: boolean) {
    onlineStatus.value = value
  }
  function getStatus() {
    return onlineStatus.value
  }

  // 给出联网情况提示变化
  function setRefresh() {
    refresh.value = new Date().toString()
  }

  return {
    onlineStatus: computed(() => onlineStatus.value),
    refresh: computed(() => refresh.value),
    setStatus,
    getStatus,
    setRefresh,
  }
})

//
//
// 窗口大小
export const useWindowSizeStore = defineStore('windowSize', () => {
  const windowWidth = ref(window.innerWidth)
  const windowHeight = ref(window.innerHeight)

  function handleResize() {
    windowWidth.value = window.innerWidth
    windowHeight.value = window.innerHeight
    // console.log('窗口大小变化', windowWidth.value, windowHeight.value)
  }

  const handleResizeDebounce = debounce(() => handleResize(), 500)

  function watchWindowResize() {
    window.addEventListener('resize', handleResizeDebounce)
  }

  return {
    windowWidth: computed(() => windowWidth.value),
    windowHeight: computed(() => windowHeight.value),
    handleResize,
    watchWindowResize,
  }
})

//
//
// 用户信息
export const useUserStore = defineStore('user', () => {
  const phone = ref<string>('')
  const email = ref<string>('')
  const userId = ref<string>('')
  const avatar = ref<string>('')
  const account = ref<string>('')
  const nickname = ref<string>('')
  const signature = ref<string>('')
  const createTime = ref<string>('')
  const loginStatus = ref<boolean>(false)

  const routes = ref<RouteItf[]>([])

  async function getUserInfo() {
    const res = await getUserInfoApi()
    if (res.code !== 200) {
      loginStatus.value = false
      window.localStorage.removeItem('token')
      routes.value = []
      return false
    }

    email.value = res.data.email
    userId.value = res.data.id
    phone.value = res.data.phoneNumber
    avatar.value = res.data.avatar
    account.value = res.data.account
    nickname.value = res.data.nickname
    signature.value = res.data.signature
    createTime.value = res.data.createTime
    loginStatus.value = true
    await getUserAccessRoutes()

    return true
  }

  function setLoginStatus() {
    loginStatus.value = false
  }
  function resetData() {
    loginStatus.value = false
    routes.value = []
    userId.value = ''
  }

  // 获取登录用户的系统访问路由
  async function getUserAccessRoutes() {
    const res = await getUserAccessRoutesApi('中心系统')
    routes.value = res.data
    // console.log(res.data)
    return res.data
  }

  // 判断用户是否拥有某个路由
  function judgeHasRoute(path: string): boolean {
    const l = routes.value.filter((item) => item.path === path)
    if (l.length > 0) return true
    else return false
  }

  return {
    phone: computed(() => phone.value),
    email: computed(() => email.value),
    userId: computed(() => userId.value),
    avatar: computed(() => avatar.value),
    account: computed(() => account.value),
    nickname: computed(() => nickname.value),
    signature: computed(() => signature.value),
    createTime: computed(() => createTime.value),
    loginStatus: computed(() => loginStatus.value),
    remoteRoutes: computed(() => routes.value),
    resetData,
    getUserInfo,
    judgeHasRoute,
    setLoginStatus,
    getUserAccessRoutes,
  }
})

//
//
// 用户脱敏认证
export const useDesensitizeVerifyStore = defineStore(
  'desensitizeVerify',
  () => {
    const key: string = 'userDesensitizeExpireTime'

    // 设置本地过期时间
    const setExpireTime = (value: string) =>
      window.localStorage.setItem(key, value)

    // 获取本地过期时间
    const getExpireTime = () => window.localStorage.getItem(key)

    // 获取用户脱敏认证状态
    const desensitizeDataVerifyStatus = async (): Promise<boolean> => {
      const res = await desensitizeDataVerifyStatusApi()

      if (res.code !== 200) {
        ElMessage.error(res.message)
        return false
      }
      return res.data
    }

    // 获取用户脱敏认证过期时间
    const getUserDesensitizeExpireTime = async () => {
      const res = await desensitizeDataVerifyExpireTimeApi()
      if (res.code !== 200) return ElMessage.error(res.message)
      setExpireTime(res.data)
    }

    // 判断是否过期
    async function judgeExpireTime() {
      const now = new Date().getTime()
      const expireTime = getExpireTime()
      const expire = new Date(expireTime).getTime()

      // 判断本地是否有过期时间标识
      if (expireTime) {
        // 当前时间是否大于过期时间
        if (now > expire) {
          // 重新获取状态
          const status = await desensitizeDataVerifyStatus()
          if (status === true) {
            // 重新设置过期时间
            await getUserDesensitizeExpireTime()
            return true
          }
          return false
        } else return true
      } else return false
    }

    // 用户脱敏认证
    async function desensitizeDataVerify(password: string): Promise<boolean> {
      const res = await desensitizeDataVerifyApi(password)

      if (res.code !== 200) {
        ElMessage.error(res.message)
        return false
      } else {
        ElMessage.success('认证成功')
        setExpireTime(res.data)
        return true
      }
    }

    return {
      judgeExpireTime,
      desensitizeDataVerify,
    }
  }
)

//
//
// 主题色
export const useThemeStore = defineStore('theme', () => {
  // 当前主题
  const theme = ref<string>('')
  // 主题选项
  const option = ref<{ [key: string]: Function }>({
    'theme-default': () => theme0,
  })

  // 主题配置
  const theme0 = {
    '--theme-background': '#c8e0e4',
    '--theme-header-background': '#7db6bf',
    '--theme-header-active': '#c8e0e4',
    '--theme-header-hover': '#8fc0c7',
  }

  // 设置主题
  function setTheme(value: string) {
    theme.value = value
    changeTheme()
  }

  // 改变主题
  function changeTheme() {
    const currentTheme = option.value[theme.value]()
    const arr: string[] = Object.keys(currentTheme)

    arr?.map((item) => {
      document.documentElement.style.setProperty(item, currentTheme[item])
    })
  }

  function tableHeaderCellStyle(): any {
    let style = {
      'background-color': '#C8E0E4',
      color: '#444444',
      'user-select': 'none',
    }

    return style
  }

  return {
    option: computed(() => option.value),
    theme: computed(() => theme.value),
    setTheme,
    tableHeaderCellStyle,
  }
})

//
//
// 分类树状列表
export const useSortTreeStore = defineStore('sortTree', () => {
  const sortTree = ref<SortTreeItf[]>([])
  const originData = ref<SortItf[]>([])
  const sortDescriptionMap = ref<{ [key: string]: string }>({})

  // 获取分类
  async function getSortList() {
    const res = await getSortListApi()
    if (res.code !== 200) return ElMessage.error(res.message)
    // ElMessage.success('获取分类成功！')
    originData.value = res.data

    const tempObj = {}
    res.data.forEach((item) => (tempObj[item.id] = item.description))
    sortDescriptionMap.value = tempObj

    const arr = formattingDataStructure(res.data)
    sortTree.value = arr
  }

  // 格式化数据，将数据格式化为树状结构
  function formattingDataStructure(arr: SortItf[], parentId = null) {
    const result = []
    for (const item of arr) {
      if (item.parentId === parentId) {
        const children = formattingDataStructure(arr, item.id)
        if (children.length > 0) {
          result.push({
            value: item.id,
            label: item.description,
            children: children,
          })
        } else {
          result.push({ value: item.id, label: item.description })
        }
      }
    }
    return result
  }

  // 格式化数据，将数据格式化为树状结构，并通过分类类型进行筛选
  function formattingSortData(arr: SortItf[], parentId = null, sortType = '') {
    const result = []
    for (const item of arr) {
      if (item.parentId === parentId) {
        const children = formattingSortData(arr, item.id, sortType)
        if (children.length > 0) {
          result.push({
            value: item.id,
            label: item.description,
            children: children,
          })
        } else {
          if (item.level == 1 || item.type == sortType)
            result.push({ value: item.id, label: item.description })
        }
      }
    }
    return result
  }

  // 通过一个 id 的值，获取到上级所有的id
  function findParentValues(tree: SortTreeItf[], targetValue: string) {
    for (const node of tree) {
      if (node.value === targetValue) {
        return [targetValue] // 返回空数组，因为已经找到了目标值
      }
      if (node.children) {
        const result = findParentValues(node.children, targetValue)
        if (result.length > 0) {
          return [node.value, ...result]
        }
      }
    }
    return [] // 没有找到目标值，返回空数组
  }

  // 通过上级的id列表，得到上级的描述字符串
  // 可以通过 findParentValues 方法获取上级的id列表
  function getDescriptionStr(ids: string[]) {
    if (ids.length === 0) return ''

    let str = ''
    ids.forEach((id) => (str += sortDescriptionMap.value[id] + ' > '))

    return str.slice(0, -3)
  }

  return {
    sortTree: computed(() => sortTree.value),
    originData: computed(() => originData.value),
    sortDescriptionMap: computed(() => sortDescriptionMap.value),
    getSortList,
    findParentValues,
    formattingSortData,
    getDescriptionStr,
  }
})
